//
//  CCNSString.m
//  CCFC_IPHONE
//
//  Created by  xuchen(陈旭)， xichen(陈曦)， qq：511272827 on 10-11-15.
//  Copyright 2010 cc_team. All rights reserved.
//

#include "CCAll.h"
#include <wchar.h>

#ifdef	OBJC_MACRO
#import "CCNSString.h"

@implementation CCNSString

// not availble
// 获取字符在字符串第一次出现的位置
+ (NSInteger)firstIndexOfChar:(NSString *)str withChar:(unichar)ch
{
	return [CCNSString firstIndexOfChar:str withChar:ch withAppearCount:1];
}

// 获取字符在字符串最后一次出现的位置
+ (NSInteger)lastIndexOfChar:(NSString *)str withChar:(unichar)ch
{
	for(NSInteger i = str.length; i >= 0; i--)
	{
		if(ch == [str characterAtIndex:i])
		{
			return i;
		}
	}
	
	return -1;		// 没找到
}

// 获取字符在字符串第N次出现的位置
+ (NSInteger)firstIndexOfChar:(NSString *)str withChar:(unichar)ch withAppearCount:(NSInteger)count
{
	NSInteger appearCount = 0;
	
	for(NSInteger i = 0; i < str.length; i++)
	{
		if(ch == [str characterAtIndex:i])
		{
			appearCount++;
			if(appearCount == count)
			{
				return i;
			}
		}
	}
	
	return -1;		// 没找到
}

+ (void)trimBegin:(INOUT NSMutableString *)str
{
	assert(str != nil);
	
	int i;
	for(i = 0; i < str.length; i++)
	{
		unichar ch = [str characterAtIndex:i];
		if(!iswspace(ch))
		{
			break;
		}
	}
	
	if(0 == i)
	{
		return;
	}
	
	[str deleteCharactersInRange:NSMakeRange(0, i)];
}

+ (void)trimEnd:(INOUT NSMutableString *)str
{
	assert(str != nil);
	
	int i;
	for(i = str.length - 1; i >= 0; i--)
	{
		unichar ch = [str characterAtIndex:i];
		if(!iswspace(ch))
		{
			break;		//从后朝前找到不是空白字符的位置
		}
	}
	
	if(i == str.length - 1)
	{
		return;
	}
	
	NSUInteger loc = i + 1;
	[str deleteCharactersInRange:NSMakeRange(loc, str.length - loc)];
}

+ (void)trim:(INOUT NSMutableString *)str
{
	assert(str != nil);
	
	[self trimBegin:str];
	[self trimEnd:str];
}

@end

#endif	//OBJC_MACRO
